package com.ruoyi.activiti.controller;

import com.alibaba.fastjson.JSON;

import com.ruoyi.activiti.security.SecurityUtils;
import com.ruoyi.activiti.until.SmsCodeUtils;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.model.payloads.StartProcessPayload;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.model.payloads.GetTasksPayload;
import org.activiti.api.task.runtime.TaskRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/activiti")
public class MerchantActivityController {

    //流程运行实例
    @Autowired
    private TaskRuntime taskRuntime;
    //任务运行实例
    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private SecurityUtils securityUtils;

    /**
     * 开始审核流程
     * @param sid
     * @return
     */
    @GetMapping("merchantreview/{sid}")
    public Map merchantreview(@PathVariable Integer sid){
        securityUtils.logInAs(String.valueOf(sid));//必须

        Map resultMap = new HashMap();
        String aid = "administrators_002";//数据库查询 CFO
        String cid = "finance_003";//数据库查询CEO

        Map vars = new HashMap<>();
        vars.put("sid",sid);
        vars.put("aid",aid);
        vars.put("cid",cid);

        Map businessKeyMap = new HashMap<>();
        businessKeyMap.put("type","merchantAudit");
        businessKeyMap.put("sid",sid);
        String businessKey = JSON.toJSONString(businessKeyMap);

        StartProcessPayload startProcessPayload = ProcessPayloadBuilder
                .start()//开始流程实例
                .withProcessDefinitionKey("approve")//指定的流程，配置文件里面流程ID
                .withVariables(vars)//关联变量,参与者Assignee
                .withBusinessKey(businessKey)//关联业务,自定义
                .build();
        ProcessInstance pi = processRuntime.start(startProcessPayload);//开启流程
        System.out.println("流程实例ID：" + pi.getId());//

        resultMap.put("ProcessInstanceId",pi.getId());

        //做事，完成任务,张三顺便完成自己的任务
        GetTasksPayload getTaskPayload = TaskPayloadBuilder
                .tasks()
                .withProcessInstanceId(pi.getId())//查询条件  流程ID
                .withAssignee(String.valueOf(sid))//参与用户
                .build();
        //根据查询条件 查询所有任务
        Page<Task> taskPage = taskRuntime.tasks(
                Pageable.of(0, 10),getTaskPayload);

        if (taskPage.getTotalItems() > 0) {//total
            for (Task task : taskPage.getContent()) {
                System.out.println("任务：" + task);
                resultMap.put("taskId",task.getId());
                //taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
                //完成任务
                taskRuntime.complete(
                        TaskPayloadBuilder.complete()
                                .withTaskId(task.getId())
                                .build());

            }
        }
        return resultMap;

    }

    /**
     * 查看代办事项
     * @param userId
     * @return
     */
    @GetMapping("/getUserTaskList/{userId}")
    public List<Task> getUserTaskList(@PathVariable String userId) {

        securityUtils.logInAs(userId);
        GetTasksPayload getTaskPayload = TaskPayloadBuilder
                .tasks()
                .withAssignee(userId)//指定参与者
                .build();
        Page<Task> taskPage = taskRuntime.tasks(
                Pageable.of(0, 1000),
                getTaskPayload);

        return taskPage.getContent();
    }

    /**
     * 根据taskID查找businessKey，查找业务信息//点击详情
     * @param taskId
     * @param userId
     * @return
     */
    @GetMapping("/getBusinessInfo/{taskId}/{userId}")
    public String getBusinessInfo(@PathVariable String taskId,
                                  @PathVariable String userId) {

        securityUtils.logInAs(userId);

        Task task = taskRuntime.task(taskId);
        String businessKey = "";
        if(task!=null){
            String processInstanceId = task.getProcessInstanceId();//根据任务 获取流程实例ID
            //通过 流程实例ID 查询ProcessInstance
            ProcessInstance processInstance = processRuntime.processInstance(processInstanceId);
            businessKey = processInstance.getBusinessKey();

            System.out.println("businessKey=" + businessKey);
        }
        return businessKey;
    }

    /**
     * 管理员 审批通过，不通过
     * @param taskId
     * @param aid
     * @param success
     * @return
     */
    @GetMapping("/adminexamine/{taskId}/{aid}/{success}")
    public Task adminexamine(@PathVariable String taskId,
                             @PathVariable String aid,
                             @PathVariable boolean success) {

        securityUtils.logInAs(aid);
        Task task = taskRuntime.task(taskId);

        if(task!=null){
            taskRuntime.complete(
                    TaskPayloadBuilder
                            .complete()
                            .withTaskId(task.getId())
                            .withVariable("adminsuccess",success)//关联任务变量
                            .build());
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = processRuntime.processInstance(processInstanceId);
            System.out.println("processInstance Status"+processInstance.getStatus());

        }
        return task;
    }

    /**
     * 财务审批通过，不通过
     * @param taskId
     * @param cid
     * @param success
     * @return
     */
    @GetMapping("/financeexamine/{taskId}/{cid}/{success}")
    public Task financeexamine(@PathVariable String taskId,
                               @PathVariable String cid,
                               @PathVariable boolean success
    ) {
        securityUtils.logInAs(cid);
        Task task = taskRuntime.task(taskId);
        if(task!=null){
            taskRuntime.complete(
                    TaskPayloadBuilder
                            .complete()
                            .withTaskId(task.getId())
                            .withVariable("financesuccess",success)//关联任务变量
                            .build());
                  //发送短信
            getNote();
            System.out.println("线程一"+Thread.currentThread().getName());
            //String processInstanceId = task.getProcessInstanceId();
            // ProcessInstance processInstance = processRuntime.processInstance(processInstanceId);
            // System.out.println("processInstance Status"+processInstance.getStatus());
        }
        return task;
    }


    @Async("taskExecutor")
    public void getNote() {
        Map map = new HashMap();
        map.put("code", 1111);
        System.out.println("线程" + Thread.currentThread().getName());
        String jsonString = JSON.toJSONString(map);
        SmsCodeUtils.sendSms("思远","SMS_158845051","18514551353",jsonString);
    }
}
